<template>
  <div id="interview">
    <div class="title">智能对话系统</div>
    <div class="wrapper">
      <el-card class="box-card" :body-style="{ padding: '20px' }">
        <el-row class="video-container" gutter={20}>
          <!-- 左侧视频流显示区域 -->
          <el-col :span="12" class="video-wrapper">
            <video v-show="videoStream" ref="video" autoplay class="video"></video>
          </el-col>

          <!-- 右侧聊天记录区域 -->
          <el-col :span="12" class="transcript-wrapper">
            <el-divider>聊天记录</el-divider>
            <el-card class="transcript-card">
              <!-- 聊天记录显示区域 -->
              <div class="chat-box" ref="chatBox">
                <div v-for="(text, index) in chatHistory" :key="index" class="chat-item">
                  <div class="chat-item-content">
                    <span class="chat-item-author">{{ text.author }}:</span>
                    <span class="chat-item-message">
                      <!-- 渲染逐字 -->
                      <span v-for="(char, charIndex) in text.displayMessage" :key="charIndex" class="char">
                        {{ char }}
                      </span>
                    </span>
                  </div>
                </div>
              </div>
            </el-card>

            <!-- 新增的用户输入框和按钮 -->
            <el-row class="user-input-row" gutter={10}>
              <el-col :span="20">
                <el-input
                  v-model="userInput"
                  placeholder="请输入您的问题"
                  clearable
                />
              </el-col>
              <el-col :span="4">
                <el-button type="primary" @click="handleUserInput">发送</el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <!-- 控制按钮 -->
        <el-row class="action-buttons-row" gutter={20}>
          <el-col :span="12" class="action-buttons">
            <el-button type="primary" @click="startMedia" size="medium">开始人脸识别</el-button>
            <el-button type="danger" @click="stopMedia" size="medium">退出人脸识别</el-button>
            <el-button type="success" @click="startRecognition" :disabled="isRecognizing" size="medium">打开麦克风</el-button>
            <el-button type="warning" @click="stopRecognition" :disabled="!isRecognizing" size="medium">关闭麦克风</el-button>
            <el-button type="danger" @click="clearChatHistory" size="medium">清除记录</el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  data() {
    return {
      videoStream: null,  // 用于存储视频流
      audioStream: null,  // 用于存储音频流
      transcript: '',  // 当前实时识别的文本
      isRecognizing: false,  // 控制语音识别的状态
      recognition: null,  // 用于存储语音识别实例
      chatHistory: [],  // 保存通话记录
      botId: 'bot-20241202150147-2n7ss',
      userId: 'user123',
      userInput: '', // 用户输入框的内容
    };
  },
  methods: {
    // 处理用户输入
    handleUserInput() {
      const userMessage = this.userInput.trim();
      if (!userMessage) {
        this.$message.warning('输入不能为空');
        return;
      }

      // 添加到聊天记录
      this.addToChatHistory('我', userMessage);

      // 清空输入框
      this.userInput = '';

      // 生成机器人回复
      this.generateResponse(userMessage);
    },
    async startMedia() {
      try {
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
          alert('浏览器不支持获取摄像头和麦克风');
          return;
        }

        const stream = await navigator.mediaDevices.getUserMedia({
          video: true,
          audio: true,
        });

        console.log('获取视频流成功', stream);

        this.$nextTick(() => {
          if (this.$refs.video) {
            this.$refs.video.srcObject = stream;
          } else {
            console.error('video 元素未找到');
          }
        });

        this.videoStream = stream;
        this.audioStream = stream;

      } catch (err) {
        console.error('获取媒体设备失败:', err);
        alert('无法访问摄像头和麦克风');
      }
    },

    stopMedia() {
      if (this.videoStream) {
        const tracks = this.videoStream.getTracks();
        tracks.forEach(track => track.stop());
        this.videoStream = null;
        this.audioStream = null;
        console.log('视频流已停止');
      }
    },

    startRecognition() {
      if (!('webkitSpeechRecognition' in window)) {
        alert('语音识别在此浏览器中不可用');
        return;
      }

      this.recognition = new webkitSpeechRecognition();
      this.recognition.continuous = true;
      this.recognition.interimResults = true;
      this.recognition.lang = 'zh-CN';

      this.recognition.onstart = () => {
        console.log('语音识别开始');
        this.isRecognizing = true;
      };

      this.recognition.onend = () => {
        console.log('语音识别结束');
        this.isRecognizing = false;
      };

      this.recognition.onresult = (event) => {
        let finalTranscript = '';
        for (let i = event.resultIndex; i < event.results.length; i++) {
          const transcript = event.results[i][0].transcript;
          if (event.results[i].isFinal) {
            finalTranscript += transcript + ' ';
            // 添加识别到的文本到聊天记录
            this.addToChatHistory('我', finalTranscript);
            // 自动生成并添加回答
            this.generateResponse(finalTranscript);
            finalTranscript = '';  // 清空当前识别结果
          } else {
            this.transcript = transcript;
          }
        }
      };

      this.recognition.start();
    },

    stopRecognition() {
      if (this.recognition) {
        this.recognition.stop();
      }
    },

    // 添加聊天记录
    addToChatHistory(author, message) {
      const newMessage = {
        author,
        message,
        displayMessage: []
      };
      this.chatHistory.push(newMessage);

      let index = 0;
      const interval = setInterval(() => {
        if (index < message.length) {
          newMessage.displayMessage.push(message[index]);
          index++;
        } else {
          clearInterval(interval);
        }
      }, 100); // 每100毫秒添加一个字

      this.$nextTick(() => {
        // 滚动到底部
        const chatBox = this.$refs.chatBox;
        chatBox.scrollTop = chatBox.scrollHeight;
      });
    },

    // 自动生成回答并发送到后端
    async generateResponse(userMessage) {
      // 构建请求参数
      // 发送请求到后端获取聊天机器人响应
      const botId = 'bot-20241203222946-t6wsm';
      const userId = 'user123';
      const encodedMessage = encodeURIComponent(userMessage);  // 对消息进行 URL 编码
      // 向后端发送请求
      try {
        const res = await axios.get('/api/chat?botId=' + botId + '&userId=' + userId + '&userMessage=' + encodedMessage);
        // 后端返回的响应包含小助手的回答
        const interviewResponse = res.data || '我没有收到有效的回应';  // 如果没有返回数据，使用默认的回答
        console.log('小助手的回答:', interviewResponse);
        // 延迟1秒后发送小助手的回答
        setTimeout(() => {
          this.addToChatHistory('小助手', interviewResponse);
        }, 0);
      } catch (error) {
        console.error('发送消息到后端失败', error);
      }
    },

    // 清空聊天记录
    clearChatHistory() {
      this.chatHistory = [];
      console.log('聊天记录已清空');
    },
  },
};
</script>

<style lang="less" scoped>
#interview {
  width: 1280px;
  margin: 0 auto;
}

.title {
  margin: 20px;
  font-size: 24px;
  font-weight: bold;
  text-align: center;
}

#interview .wrapper {
  background-color: #fff;
  padding: 20px;
}

.video-container {
  display: flex;
  justify-content: space-between;
}

.video-wrapper {
  width: 600px;
  height: 660px;  /* 控制视频高度 */
  position: relative;
}

.video {
  width: 100%;
  height: 100%;
  object-fit: cover;  /* 保持视频比例，裁剪多余部分 */
}

.transcript-wrapper {
  padding: 20px;
  max-height: 750px;
  overflow-y: hidden;
}

.transcript-card {
  padding: 20px;
  background-color: #f9f9f9;
}

.chat-box {
  height: 500px;
  max-height: 600px;
  overflow-y: auto;
}

.chat-item {
  margin-bottom: 15px;
}

.chat-item-content {
  display: flex;
  flex-direction: column;
}

.chat-item-author {
  font-weight: bold;
  color: #409EFF;
}

.chat-item-message {
  color: #333;
  margin-left: 10px;
}

.char {
  display: inline-block;
  opacity: 0;
  animation: fadeIn 0.3s forwards;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.action-buttons-row {
  margin-top: 20px;
  display: flex;
  justify-content: flex-start;
}

.action-buttons {
  width: 100%;
  display: flex;
  justify-content: flex-start;  /* 按钮两端留空隙 */
}

.user-input-row {
  width: 100%; /* 确保宽度与聊天区域一致 */
  margin-top: 10px;
  display: flex;
  align-items: center;
}

.user-input-row .el-input {
  width: 100%; /* 确保输入框占满父容器 */
}

.user-input-row .el-button {
  width: 100%; /* 确保按钮宽度与输入框一致 */
}


.chat-box {
  max-height: 100%; /* 确保内部滚动 */
  overflow-y: auto;
}

.user-input-row {
  margin-top: 10px;
}

</style>
